#if UNITY_EDITOR

using System.IO;
using System.Diagnostics;
using UnityEditor;
using UnityEngine;
using Debug = UnityEngine.Debug;

public class DataTableBuild
{
    [MenuItem("Tools/BuildDatas")]
    public static void BuildDataTables()
    {
        // 1. ִ�� gen_client.bat
        string projectRoot = Directory.GetParent(Application.dataPath).FullName;
#if UNITY_EDITOR_OSX
        string batPath = Path.Combine(projectRoot, "DataTables", "gen_client.sh");
#else
        string batPath = Path.Combine(projectRoot, "DataTables", "gen_client.bat");

#endif

        if (!File.Exists(batPath))
        {
            Debug.LogError($"δ�ҵ��������ļ�: {batPath}");
            return;
        }
#if UNITY_EDITOR_OSX
        
        
        // 创建进程启动信息
        ProcessStartInfo psi = new ProcessStartInfo
        {
            FileName = "/bin/bash",  // 使用bash解释器
            WorkingDirectory = Path.GetDirectoryName(batPath),
            UseShellExecute = false,
            CreateNoWindow = true,
            RedirectStandardOutput = true,
            RedirectStandardError = true
        };
#else
        ProcessStartInfo psi = new ProcessStartInfo
        {
            FileName = batPath,
            WorkingDirectory = Path.GetDirectoryName(batPath),
            CreateNoWindow = true,
            UseShellExecute = false,
            RedirectStandardOutput = true,
            RedirectStandardError = true
        };
#endif


        try
        {
            using (Process process = Process.Start(psi))
            {
                string output = process.StandardOutput.ReadToEnd();
                string error = process.StandardError.ReadToEnd();
                process.WaitForExit();
                Debug.Log($"gen_client.bat  {process.StandardOutput.ReadToEnd()}");

                if (process.ExitCode != 0)
                {
                    Debug.LogError($"gen_client.bat error: {process.ExitCode}\n{error}");
                    return;
                }
                else
                {
                    Debug.Log($"gen_client.bat ִsuccess \n{output}");
                }
            }
        }
        catch (System.Exception ex)
        {
            Debug.LogError($"ִ�� gen_client.bat Exception {ex.Message}");
            return;
        }

        // 2. �����ɵ�DataTable�ļ�
        string dataTablePath = Path.Combine(Application.streamingAssetsPath, "DataTables");
        if (Directory.Exists(dataTablePath))
        {
            Directory.Delete(dataTablePath, true);
            Debug.Log("DataTable");
        }
        // 3. �����µ�DataTable�ļ�
        CopyDataTablesToStreamingAssets();

        AssetDatabase.Refresh();
    }

    /// <summary>
    /// ��Assets/DataTables/Ŀ¼�µ������ļ�������StreamingAssetsĿ¼��
    /// </summary>
    public static void CopyDataTablesToStreamingAssets()
    {
        string sourceDir = Path.Combine(Application.dataPath, "DataTables");
        string targetDir = Application.streamingAssetsPath;

        if (!Directory.Exists(sourceDir))
        {
            Debug.LogWarning($"ԴĿ¼������: {sourceDir}");
            return;
        }

        if (!Directory.Exists(targetDir))
        {
            Directory.CreateDirectory(targetDir);
        }

        string[] files = Directory.GetFiles(sourceDir, "*", SearchOption.AllDirectories);
        foreach (var file in files)
        {
            // ���� .meta �ļ�
            if (file.EndsWith(".meta"))
                continue;
            string relativePath = file.Substring(sourceDir.Length + 1);
            string destFile = Path.Combine(targetDir, relativePath)+".txt";

            string destDir = Path.GetDirectoryName(destFile);
            if (!Directory.Exists(destDir))
            {
                Directory.CreateDirectory(destDir);
            }

            File.Copy(file, destFile, true);
        }

        Debug.Log("DataTables copy  done");
    }
}
#endif
